<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class TiApply2 extends Common
{

	//列表
    public function index()
    {

        $where = [];
        $sn = $this->request->get('sn');
        $this->assign('sn',$sn);
        if($sn){
            $where['sn'] = ['like',"%$sn%"];
        }
        $title = $this->request->get('title');
        $this->assign('title',$title);
        if($title){
            $where['title'] = ['like',"%$title%"];
        }
        $status = $this->request->get('status');
        $this->assign('status',$status);
        if($status){
            $where['status'] = $status;
        }
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);
        if($start&&$end){
            $where['ctime'] = ['between',[strtotime($start),strtotime($end)]];
        }elseif($start){
            $where['ctime'] = ['>',strtotime($start)];
        }elseif($end){
            $where['ctime'] = ['<',strtotime($end)];
        }
        $count = Db::table('cg_ti t')->where($where)->count();
        $data = Db::table('cg_ti t')->order("t.id desc")->where($where)->paginate(10,$count);

//        echo Db::table('cg_ti')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('employee')->where(array('id'=>$v['cuser']))->value('em_name');
            $data[$k]['pusername'] = Db::table('employee')->where(array('id'=>$v['puser']))->value('em_name');
            $data[$k]['cate_title'] = Db::table('cg_ti_cate')->where(array('id'=>$v['cate_id']))->value('title');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
            switch ($v['status']){
                case 2:
                    $data[$k]['status_title'] = '已打回';
                    break;
                case 3:
                    $data[$k]['status_title'] = '区域领导审批';
                    break;
                case 4:
                    $data[$k]['status_title'] = '拆分人审批';
                    break;
                case 5:
                    $data[$k]['status_title'] = '集团领导审批';
                    break;
                case 6:
                    $data[$k]['status_title'] = '抄送';
                    break;
                case 7:
                    $data[$k]['status_title'] = '已归档';
                    break;
                case 8:
                    $data[$k]['status_title'] = '已作废';
                    break;
                case 9:
                    $data[$k]['status_title'] = '已否决';
                    break;
                default:
                    $data[$k]['status_title'] = '草稿';
            }
        }

        $this->assign('data',$data);
        $this->assign('page',$page);

        return $this->fetch();
    }

    public function add(){
        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');
            $ti_id = $this->request->post('ti_id');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }

            $bool = Db::table('cg_ti')->where('id',$ti_id)->update($data);
            if(false !== $bool){

                //更新附件表
                if(isset($attachids)){

                    Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$ti_id,'target_table'=>'cg_ti'));

                }

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$ti_id]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"添加成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"添加失败"
                ]);die;
            }

        }
        $this->template();
        return $this->fetch('form');
    }

    //添加数据
    public function addData(){

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        return $this->fetch('addData');
    }

    //修改数据行
    public function updateData(){
        $id = $this->request->get('id');

        if($_POST){

            $validate = new Valid([
                'start|促销执行时间'  => 'require|dateFormat:Y-m-d',
                'end|促销执行时间'  => 'require|dateFormat:Y-m-d|gt:start',
                'head|负责人'  => 'require',
                'expCanTime|预计核销时间'  => 'require|dateFormat:Y-m-d',
                'totalExpectedSales|总预计销量'  => 'require',
                'totalBenchmarkSales|总基准销量'  => 'require',
                'feetype|费用类型'  => 'require',
                'amount|未税总额'  => 'require',
                'paymethod|费用支付方式'  => 'require',
                'jrbm|费用计入部门'  => 'require',
                'project|费用计入方案'  => 'require',
            ]);
            $data = [];
            $data['net'] = $this->request->post('net');
            $data['start'] = $this->request->post('start');
            $data['end'] = $this->request->post('end');
            $data['head'] = $this->request->post('head');
            $data['expCanTime'] = $this->request->post('yjverifyTime');
            $data['totalExpectedSales'] = $this->request->post('totalExpectedSales');
            $data['totalBenchmarkSales'] = $this->request->post('totalBenchmarkSales');
            $data['feetype'] = $this->request->post('feetype');
            $data['amount'] = $this->request->post('amount');
            $data['paymethod'] = $this->request->post('paymethod');
            $data['buhuo'] = $this->request->post('buhuo');
            $data['jrbm'] = $this->request->post('jrbm');
            $data['project'] = $this->request->post('project');
            $data['brief'] = trim($this->request->post('brief'));

            $arealat= trim($this->request->post('arealat'));
            switch ($arealat){
                case 1:
                    $data['net'] = $this->request->post('net');
                    if(!$data['net']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择网点"
                        ]);die;
                    }
                    break;
                default:

            }
            $productlat= trim($this->request->post('productlat'));
            switch ($productlat){
                case 1:
                    $data['brand'] = $this->request->post('brand');
                    if(!$data['brand']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择品牌"
                        ]);die;
                    }
                    break;
                case 2:
                    $data['category'] = $this->request->post('category');
                    if(!$data['category']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择品类"
                        ]);die;
                    }
                    break;
                case 3:
                    $data['series'] = $this->request->post('series');
                    if(!$data['series']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择系列"
                        ]);die;
                    }
                    break;
                case 4:
                    $data['sku'] = $this->request->post('sku');
                    if(!$data['sku']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择sku"
                        ]);die;
                    }
                    break;
                default:
                    $data['product'] = $this->request->post('product');
                    if(!$data['product']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择单品"
                        ]);die;
                    }
            }

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $data['expCanTime'] = strtotime($data['expCanTime']);
            $data['start'] = strtotime($data['start']);
            $data['end'] = strtotime($data['end']);

            //修改其他
            $bool = Db::table('cg_ti_list')->where('id',$id)->update($data);
            if(false !== $bool){
//                echo db('cg_ti_list')->getLastSql();
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
        }

        $this->template();

        //查询非常规促销明细
        if($id){
            $list = db('cg_ti_list')->where('id',$id)->find();
            $list['jxs_title'] = db('cg_jxs')->where('id',$list['jxs_id'])->value('title');
            $list['net_title'] = db('cg_net')->where('id',$list['net'])->value('title');
            $list['brand_title'] = db('pro_brands')->where('id',$list['brand'])->value('brand_name');
            $list['category_title'] = db('pro_category')->where('id',$list['category'])->value('category_name');
            $list['series_title'] = db('pro_series')->where('id',$list['series'])->value('series_name');
            $list['sku_title'] = db('pro_sku')->where('id',$list['sku'])->value('sku_name');
            $list['product_title'] = db('pro_products')->where('id',$list['product'])->value('pro_name');
            $list['feetype_title'] = db('cg_feiyongkemu3')->where('id',$list['feetype'])->value('title');
            $list['jrbm_title'] = db('cg_fijiruzd')->where('id',$list['jrbm'])->value('title');
            $ti = db('cg_ti')->where('id',$list['ti_id'])->field('arealat,productlat')->find();
            $list = array_merge($list,$ti);
            $this->assign('list',$list);
        }

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        return $this->fetch('updateData');
    }

    //添加费用项目行
    public function addFeiyong(){
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fijiru = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fijiru);

        $str = '';
        foreach($fipay as $k=>$v){
            $str .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
        $str2 = '';
        foreach($fijiru as $k=>$v){
            $str2 .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }

        $name = 'a'.mt_rand();
        echo <<<EOF
<tr class="data">
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control feetype" name="feetype" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary feetree" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <input type="radio" name="{$name}" value="0" class="payee" checked>经销商&nbsp;
                    <input type="radio" name="{$name}" value="1" class="payee" disabled>供应商

                </td>
                <td><input type="text" name="amount" class="form-control"></td>
                <td>
                    <select name="paymethod"  class="form-control">
                        <option value="">请选择</option>
                        {$str}
                    </select>
                </td>
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control jrbm" name="jrbm" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">f111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary select_jrbm" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <select name="project" class="form-control">
                        <option value="">请选择</option>
                        {$str2}
                    </select>
                </td>
                <td class="text-center">
                    <button class="btn btn-danger del_fi_item" type="button">删除</button>
                </td>
            </tr>
EOF;

    }


    public function produceSN(){
        //生成编号
        $max = db('cg_ti')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    public function producefbSN(){
        //生成编号
        $max = db('all_ti_feeback_list')->where('no','like',date('Ymd').'%')->max('no'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //提交整个费用项目
    public function appendRow(){

        $ti_id = $this->request->post('ti_id');

        $list = $this->request->post('list/a');
        $start = $this->request->post('start');
        $end = $this->request->post('end');
        $yjverifyTime = $this->request->post('yjverifyTime');
        $totalExpectedSales = $this->request->post('totalExpectedSales');
        $totalBenchmarkSales = $this->request->post('totalBenchmarkSales');
        $jxs = $this->request->post('jxs');
        $jxs_id = $this->request->post('jxs_id');
        $head = $this->request->post('head');
        $brief = $this->request->post('brief');
        $net = $this->request->post('net/a');
        $brand = $this->request->post('brand/a');
        $category = $this->request->post('category/a');
        $series = $this->request->post('series/a');
        $sku = $this->request->post('sku/a');
        $product = $this->request->post('product/a');

        if(!$jxs_id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"请选择经销商"
            ]);die;
        }

        //保存
        $insert = [];

        //总条数
        $totalCnt = count($list);
        //如果选择网点
        if($net){

            $totalCnt *= count($net);
            foreach($net as $net_k=>$net_v){
                //如果选择的品牌
                if($brand){
                    $totalCnt = $totalCnt*count($brand);
                    foreach($brand as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['amount'] = $v['amount'];
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net'] = $net_v;//网点
                            $data['brand'] = $vv;//品牌
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|gt:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net|网点'  => 'require',
                                'brand|品牌'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择的品类
                if($category){
                    $totalCnt = $totalCnt*count($category);
                    foreach($category as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['amount'] = $v['amount'];
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net'] = $net_v;//网点
                            $data['category'] = $vv;//品类
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量
                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net|网点'  => 'require',
                                'category|品类'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择系列
                if($series){
                    $totalCnt = $totalCnt*count($series);
                    foreach($series as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['amount'] = $v['amount'];
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net'] = $net_v;//网点
                            $data['series'] = $vv;//系列
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net|网点'  => 'require',
                                'series|系列'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择sku
                if($sku){
                    $totalCnt = $totalCnt*count($sku);
                    foreach($sku as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['amount'] = $v['amount'];
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net'] = $net_v;//网点
                            $data['sku'] = $vv;//系列
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net|网点'  => 'require',
                                'sku'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择单品
                if($product){
                    $totalCnt = $totalCnt*count($product);
                    foreach($product as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['amount'] = $v['amount'];
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net'] = $net_v;//网点
                            $data['product'] = $vv;//单品
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net|网点'  => 'require',
                                'product|单品'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }
            }
        }else{ //如果选择经销商

            //如果选择的品牌
            if($brand){
                $totalCnt *= count($brand);
                foreach($brand as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['amount'] = $v['amount'];
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['brand'] = $vv;//品牌
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'brand|品牌'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择的品类
            if($category){
                $totalCnt *= count($category);
                foreach($category as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['amount'] = $v['amount'];
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['category'] = $vv;//品类
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'category|品类'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择系列
            if($series){
                $totalCnt *= count($series);
                foreach($series as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['amount'] = $v['amount'];
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['series'] = $vv;//系列
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'series|系列'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择sku
            if($sku){
                $totalCnt *= count($sku);
                foreach($sku as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['amount'] = $v['amount'];
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['sku'] = $vv;//系列
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'sku'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择单品
            if($product){
                $totalCnt *= count($product);
                foreach($product as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['amount'] = $v['amount'];
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['product'] = $vv;//单品
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'product|单品'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }
        }

        //判断是否存在费用类型相同收款方也相同的情况 ---暂时待做

        //根据经销商一些信息
        $jxs_info = db('cg_jxs')->where('id',$jxs_id)->field('zoning,provice,city')->find();
        $jxs_info['zoning'] = db('cg_market_zoning')->where('id',$jxs_info['zoning'])->value('title');
        $jxs_info['provice'] = db('cg_market_provice')->where('id',$jxs_info['provice'])->value('title');
        $jxs_info['city'] = db('cg_market_city')->where('id',$jxs_info['city'])->value('title');


        //如果主表存在
        if($ti_id){
            //查询主表编号
            $insert_sn = db('cg_ti')->where('id',$ti_id)->value('sn');
            $basic = db('cg_ti_list')->where('ti_id',$ti_id)->max('sn'); //编号递增开始位置基础

        }else{ //如果主表不存在

            $insert_sn = $this->produceSN();//生成编号
            $ti_title = $this->request->post('ti_title');
            $ti_arealat = $this->request->post('ti_arealat');
            $ti_productlat = $this->request->post('ti_productlat');
            $ti_jxs_id = $this->request->post('ti_jxs_id');

            db('cg_ti')->insert([
                'sn'=>$insert_sn,
                'title'=>$ti_title,
                'arealat'=>$ti_arealat,
                'productlat'=>$ti_productlat,
                'jxs_id'=>$ti_jxs_id,
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
            ]);
            $ti_id = db('cg_ti')->getLastInsID();
            $basic = 0; //编号递增开始位置基础
        }


        $yjverifyTime1 = strtotime($yjverifyTime);
        $start1 = strtotime($start);
        $end1 = strtotime($end);

        foreach($insert as $k=>$v){
            $v['sn'] = ($basic+$k+1);
            $v['expCanTime'] = $yjverifyTime1;
            $v['start'] = $start1;
            $v['end'] = $end1;
            $v['ctime'] = time();
            $v['ptime'] = time();
            $v['cuser'] = Session::get('employee_id');
            $v['puser'] = Session::get('employee_id');
            $v['ti_id'] = $ti_id;
            $v['shuilv'] = 6; //税率
            $v['isVAT'] = 0; //是否增值税,0否，1是
            $v['hanshui'] = $v['amount']*(1+6/100); //含税费用金额
            $v['fb_shijitourufeiyong'] = $v['hanshui']; //实际揉入费用
            $v['yujifeiyonglv'] = $v['hanshui']/$v['totalExpectedSales']*100; //预计费用率
            $v['2srjizhun'] = 0; //2sr基准销量
            $v['yujiroi'] = 0; //预计rio
            $v['status'] = 0; //状态0，正常
            $insert[$k] = $v;
            db('cg_ti_list')->insert($v);
            $insert[$k]['id'] = db('cg_ti_list')->getLastInsID();
        }

        $data = Db::table('cg_ti')->where('id',$ti_id)->find();

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';

        //明细table
        $str = $this->feeList($ti_id,$data['arealat'],$data['arealat_title'],$data['productlat'],$data['productlat_title'],$data['jxs_id'],$data['jxs_title'],$data['sn']);


        echo  json_encode([
            "success"=>true,
            "data"=>$str,
            "ti_id"=>$ti_id,
            "jxs_info"=>$jxs_info['zoning'].'&nbsp;'.$jxs_info['provice'].'&nbsp;'.$jxs_info['city'].'&nbsp;性质：经销'
        ]);die;

    }

    //明细table

    /**
     * @param $id ti_id
     * @param $arealat 区域纬度类型
     * @param $arealat_title 区域纬度标题
     * @param $productlat 产品纬度类型
     * @param $productlat_title 产品纬度标题
     * @param $jxs_id 经销商id
     * @param $jxs_title 经销商标题
     * @param $sn ti编号
     * @return string
     */
    private function feeList($id,$arealat,$arealat_title,$productlat,$productlat_title,$jxs_id,$jxs_title,$sn){


        //查询明细列表
        if($arealat==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi');//小计-预计rio
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net')->field('net')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('yujiroi');//小计-预计rio
            }
        }

        $st_amount = db('cg_ti_list')->where(['ti_id'=>$id])->sum('amount');//总计-未税费用金额
        $st_hanshui = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $st_shijitourufeiyong = db('cg_ti_list')->where(['ti_id'=>$id])->sum('fb_shijitourufeiyong');//总计-实际投入费用
        $st_shijitourufeiyong = round($st_shijitourufeiyong,2);
        $st_yujixiaoliang = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $st_yujixiaoliang = round($st_yujixiaoliang,2);
        $st_yujifeiyonglv = $st_hanshui/$st_yujixiaoliang*100;//总计-预计费用率
        $st_yujifeiyonglv = round($st_yujifeiyonglv,2);
        $st_2srjizhun = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $st_jizhunxiaoliang = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $st_jizhunxiaoliang = round($st_jizhunxiaoliang,2);
        $st_yujiroi = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi');//总计-预计rio

        //表格标头
        $mc = "<td style=\"min-width:120px\">{$arealat_title}</td>";
        $prolat = "<td style=\"min-width:100px\">{$productlat_title}</td>";
        $str = <<<EOF
                    <thead>
            <tr class="info">
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td style="min-width:80px">序号</td>
                <td style="min-width:160px">明细编号</td>
                {$mc}
                <td style="min-width: 200px">活动执行时间</td>
                <td style="min-width: 100px">预计核销时间</td>
                {$prolat}
                <td style="min-width: 100px">三级费用科目</td>
                <td style="min-width: 100px">费用支付方式</td>
                <td style="min-width: 100px">未税费用金额</td>
                <td style="min-width: 100px">税率</td>
                <td style="min-width: 100px">是否增值税(可抵扣)</td>
                <td style="min-width: 100px">含税费用金额</td>
                <td style="min-width: 100px">实际投入费用</td>
                <td style="min-width: 100px">预计销量</td>
                <td style="min-width: 100px">预计费用率</td>
                <td style="min-width: 100px">2SR基准销量</td>
                <td style="min-width: 100px">基准销量</td>
                <td style="min-width: 100px">预计ROI</td>
                <td style="min-width: 100px">备注</td>
                <td style="min-width: 100px">状态</td>
                <td style="min-width: 100px">提交人</td>
                <td style="min-width: 100px">修改人</td>
                <td style="min-width: 100px">费用计入部门</td>
                <td style="min-width: 100px">费用计入方案</td>
                <td style="min-width: 100px">收款方</td>
            </tr>
            </thead>
EOF;

        $str .= '<tbody>';
        $i = 0;
        foreach($list as $kk=>$vv) {

            foreach($vv['_child'] as $k=>$v){
                $i++;
                $feetype = $v['feetype'];
                $feetype_title = db('cg_feiyongkemu3')->where('id',$feetype)->value('title');
                $paymethod = $v['paymethod'];
                $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');
                $project = $v['project'];
                $project_title = db('cg_fijiru')->where('id',$project)->value('title');
                $jrbm = $v['jrbm'];
                $jrbm_title = db('cg_fijiruzd t')->join('department t2','t.title = t2.id')->where('t.id',$jrbm)->value('t2.de_name');
                $payee = $v['payee'];
                if($payee==0){
                    $payee = '(经销商)'.db('cg_jxs')->where('id',$jxs_id)->value('title');
                }else{
                    $payee = '(供应商)'; //供应商-待做
                }

                if($arealat==2){
                    $net_title = db('cg_net')->where('id',$v['net'])->value('title');
                    $mc = "<td>{$net_title}</td>";
                }else{
                    $mc = "<td>{$jxs_title}</td>";
                }
                if($productlat==1){
                    $temp = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==2){
                    $temp = db('pro_category')->where('id',$v['category'])->value('category_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==3){
                    $temp = db('pro_series')->where('id',$v['series'])->value('series_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==4){
                    $temp = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
                    $prolat = "<td>{$temp}</td>";
                }else{
                    $temp = db('pro_products')->where('id',$v['product'])->value('pro_name');
                    $prolat = "<td>{$temp}</td>";
                }
                $budan = $v['start']<$v['ctime']?'<span style="display:inline-block;border:1px solid red;color:red;padding:2px 5px;">补单</span>':'';
                $v['start'] = date('Y-m-d',$v['start']);
                $v['end'] = date('Y-m-d',$v['end']);
                $v['expCanTime'] = date('Y-m-d',$v['expCanTime']);
                $v['cuser_name'] = db('employee')->where('id',$v['cuser'])->value('em_name');

                $str .= <<<EOF
        <tr>
            <td>
                <input type="checkbox" name="items" value="{$v['id']}">
            </td>
            <td>
                <button class="btn btn-success upThis" data-id="{$v['id']}">修改</button>
                <button class="btn btn-danger delThis" data-id="{$v['id']}">删除本条</button>
            </td>
            <td>{$i}{$budan}</td>
            <td>{$sn}-{$v['sn']}</td>
            {$mc}
            <td>{$v['start']}-{$v['end']}<input type="hidden" name="end" value="{$v['end']}"><input type="hidden" name="start" value="{$v['start']}"></td>
            <td>{$v['expCanTime']}<input type="hidden" name="expCanTime" value="{$v['expCanTime']}"></td>
            {$prolat}
            <td>{$feetype_title}<input type="hidden" name="feetype" value="{$feetype}"></td>
            <td>{$paymethod_title}<input type="hidden" name="paymethod" value="{$paymethod}"></td>
            <td>{$v['amount']}<input type="hidden" name="amount" value="{$v['amount']}"></td>
            <td>6%</td>
            <td>否</td>
            <td>{$v['hanshui']}</td>
            <td>{$v['fb_shijitourufeiyong']}</td>
            <td>{$v['totalExpectedSales']}</td>
            <td>{$v['yujifeiyonglv']}%</td>  
            <td>{$v['2srjizhun']}</td>
            <td>{$v['totalBenchmarkSales']}</td>
            <td>{$v['yujiroi']}</td>
            <td>{$v['brief']}</td>
            <td>正常</td>
            <td>{$v['cuser_name']}</td>
            <td>&nbsp;</td>
            <td>{$jrbm_title}<input type="hidden" name="jrbm" value="{$v['jrbm']}"></td>
            <td>{$project_title}<input type="hidden" name="project" value="{$v['project']}"></td>
            <td>{$payee}<input type="hidden" name="payee" value="{$v['payee']}"></td>
        </tr>
EOF;
            }

            //小计
            $str .= <<<EOF
        <tr>
            <td colspan="2">
            </td>
            <td colspan="4" class="text-right">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$vv['st_amount']}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$vv['st_hanshui']}</td>
            <td>{$vv['st_shijitourufeiyong']}</td>
            <td>{$vv['st_yujixiaoliang']}</td>
            <td>{$vv['st_yujifeiyonglv']}%</td>
            <td>{$vv['st_2srjizhun']}</td>
            <td>{$vv['st_jizhunxiaoliang']}</td>
            <td>{$vv['st_yujiroi']}</td>
            <td colspan="7">&nbsp;</td>
        </tr>
EOF;

        }

        $str .= '</tbody>';
        $str .= <<<EOF
            <tfoot>
                <tr>
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td colspan="4" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">{$st_amount}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">{$st_hanshui}</td>
                <td class="text-right font-bold">{$st_shijitourufeiyong}</td>
                <td class="text-right font-bold">{$st_yujixiaoliang}</td>
                <td class="text-right font-bold">{$st_yujifeiyonglv}%</td>
                <td class="text-right font-bold">{$st_2srjizhun}</td>
                <td class="text-right">{$st_jizhunxiaoliang}</td>
                <td class="text-right">{$st_yujiroi}</td>
                <td colspan="7">&nbsp;</td>
            </tr>
            </tfoot>
EOF;

        return $str;
    }

    //删除行
    /**
     * 修改附件--新增、修改申请时
     * @return mixed
     */
    private function updateAttach(){
        $attach = $this->request->post('attach');
        $id = $this->request->param('id');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }

    public function delItem(){
        $ids = $this->request->param('ids');
        if(!$ids){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti_list')->where('id','in',$ids)->delete();
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    /**
     * 修改附件--异动取消等动作时
     * @return mixed
     */
    private function updateAttach2($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti')->where('id',$id)->value('fb_attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['fb_attach'] = $attach;
        Db::table('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }
    /**
     * 修改附件--核销
     * @return mixed
     */
    private function updateAttach3($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti_hexiao')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti_hexiao')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti_hexiao'));
        }

    }


    /**
     * 修改附件--反馈动作时
     * @return mixed
     */
    private function updateAttach_fb($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('all_ti_feeback_list')->where('id',$id)->value('fujian');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['fujian'] = $attach;
        Db::table('all_ti_feeback_list')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'all_ti_feeback_list'));
        }

    }

    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //修改附件
            $this->updateAttach();

            //修改其他
            $bool = Db::table('cg_ti')->where('id',$id)->update($data);
            if(false !== $bool){

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$id]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $this->template();

        $data = Db::table('cg_ti')->where('id',$id)->find();

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';
        $this->assign('data',$data);
        $this->assign('id',$id);


        $str = $this->feeList($id,$data['arealat'],$data['arealat_title'],$data['productlat'],$data['productlat_title'],$data['jxs_id'],$data['jxs_title'],$data['sn']);
        $this->assign('str',$str);


        //查询附件
        if($data['attach']){
            $attach = unserialize($data['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
            $this->assign('attach',$attach);
        }


        return $this->fetch('form');
    }
    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update_bak(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //修改附件
            $this->updateAttach();

            //修改其他
            $bool = Db::table('cg_ti')->where('id',$id)->update($data);
            if(false !== $bool){

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$id]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_ti')->where('id',$id)->find();

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';
        $this->assign('data',$data);
        $this->assign('id',$id);

        //查询明细列表
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net')->field('net')->select();
        foreach($list as $k=>$v){
            $list[$k]['_child'] = db('cg_ti_list')->where('net',$v['net'])->select();
        }
        dump($list);die;
        $this->assign('list',$list);


        //表格标头
            $mc = "<td style=\"min-width:120px\">{$data['arealat_title']}</td>";
            $prolat = "<td style=\"min-width:100px\">{$data['productlat_title']}</td>";
        $str = <<<EOF
                    <thead>
            <tr class="info">
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td style="min-width:80px">序号</td>
                <td style="min-width:120px">明细编号</td>
                {$mc}
                <td style="min-width: 200px">活动执行时间</td>
                <td style="min-width: 100px">预计核销时间</td>
                {$prolat}
                <td style="min-width: 100px">三级费用科目</td>
                <td style="min-width: 100px">费用支付方式</td>
                <td style="min-width: 100px">未税费用金额</td>
                <td style="min-width: 100px">税率</td>
                <td style="min-width: 100px">是否增值税(可抵扣)</td>
                <td style="min-width: 100px">含税费用金额</td>
                <td style="min-width: 100px">实际投入费用</td>
                <td style="min-width: 100px">预计销量</td>
                <td style="min-width: 100px">预计费用率</td>
                <td style="min-width: 100px">2SR基准销量</td>
                <td style="min-width: 100px">基准销量</td>
                <td style="min-width: 100px">预计ROI</td>
                <td style="min-width: 100px">备注</td>
                <td style="min-width: 100px">状态</td>
                <td style="min-width: 100px">提交人</td>
                <td style="min-width: 100px">修改人</td>
                <td style="min-width: 100px">费用计入部门</td>
                <td style="min-width: 100px">费用计入方案</td>
                <td style="min-width: 100px">收款方</td>
            </tr>
            </thead>
EOF;


        $str .= '<tbody>';
        $subtotal = 0;
        foreach($list as $k=>$v) {
            $feetype = $v['feetype'];
            $feetype_title = db('cg_feiyongkemu3')->where('id',$feetype)->value('title');
            $paymethod = $v['paymethod'];
            $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');
            $project = $v['project'];
            $project_title = db('cg_fijiru')->where('id',$project)->value('title');
            $jrbm = $v['jrbm'];
            $jrbm_title = db('cg_fijiruzd t')->join('department t2','t.title = t2.id')->where('t.id',$jrbm)->value('t2.de_name');
            $payee = $v['payee'];
            if($payee==0){
                $payee = $data['jxs_id'];
            }else{
                $payee = $data['jxs_id']; //供应商-待做
            }
            $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');

            if($data['arealat']==2){
                $net_title = db('cg_net')->where('id',$v['net'])->value('title');
                $mc = "<td>{$net_title}</td>";
            }else{
                $mc = "<td>{$data['jxs_title']}</td>";
            }
            if($data['productlat']==1){
                $temp = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==2){
                $temp = db('pro_category')->where('id',$v['category'])->value('category_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==3){
                $temp = db('pro_series')->where('id',$v['series'])->value('series_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==4){
                $temp = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
                $prolat = "<td>{$temp}</td>";
            }else{
                $temp = db('pro_products')->where('id',$v['product'])->value('pro_name');
                $prolat = "<td>{$temp}</td>";
            }
            $v['start'] = date('Y-m-d',$v['start']);
            $v['end'] = date('Y-m-d',$v['end']);
            $v['expCanTime'] = date('Y-m-d',$v['expCanTime']);

            $str .= <<<EOF
        <tr>
            <td>
                <input type="checkbox" name="items" value="{$v['id']}">
            </td>
            <td>
                <button class="btn btn-success upThis" data-id="{$v['id']}">修改</button>
                <button class="btn btn-danger delThis" data-id="{$v['id']}">删除本条</button>
            </td>
            <td>{$k}</td>
            <td>{$v['sn']}</td>
            {$mc}
            <td>{$v['start']}-{$v['end']}<input type="hidden" name="end" value="{$v['end']}"><input type="hidden" name="start" value="{$v['start']}"></td>
            <td>{$v['expCanTime']}<input type="hidden" name="expCanTime" value="{$v['expCanTime']}"></td>
            {$prolat}
            <td>{$feetype_title}<input type="hidden" name="feetype" value="{$feetype}"></td>
            <td>{$paymethod_title}<input type="hidden" name="paymethod" value="{$paymethod}"></td>
            <td>{$v['amount']}<input type="hidden" name="amount" value="{$v['amount']}"></td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>  
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$jrbm_title}<input type="hidden" name="jrbm" value="{$v['jrbm']}"></td>
            <td>{$project_title}<input type="hidden" name="project" value="{$v['project']}"></td>
            <td>{$payee}<input type="hidden" name="payee" value="{$v['payee']}"></td>
        </tr>
EOF;
        }
        $str .= '</tbody>';
        $str .= <<<EOF
            <tfoot>
                <tr>
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td colspan="3" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td>-</td>
                <td class="text-right">0.00</td>
                <td class="text-right">0.00</td>
                <td colspan="8">&nbsp;</td>
            </tr>
            </tfoot>
EOF;
        $this->assign('str',$str);


        //查询附件
        if($data['attach']){
            $attach = unserialize($data['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch('form');
    }

    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti')->where(array('id'=>$id))->delete();
        if(false !== $bool){
            db('cg_ti_list')->where('ti_id',$id)->delete();
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择费用科目3
    public function selectFee(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择费用计入部门
    public function selectJrbm(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择网点
    public function selectNet(){
        return $this->fetch();
    }
    //选择品牌
    public function selectBrands(){
        return $this->fetch();
    }
    //选择品类
    public function selectCategory(){
        return $this->fetch();
    }
    //选择系列
    public function selectSeries(){
        return $this->fetch();
    }
    //选择sku
    public function selectSKU(){
        return $this->fetch();
    }

    //选择单品
    public function selectProduct(){
        return $this->fetch();
    }
    //添加补货明细
    public function addbhlist(){
        if($_POST){
            dump($_POST);
            $data = $this->request->post('data/a');

            foreach($data as $k=>$v){
                $valid = new Valid([
                    'product|样品或物料'=>'required',
                    'num|数量'=>'required|number|>:0',
                ]);
                $bool = $valid->check($v);
                if(false==$bool){
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$valid->getError()
                    ]);die;
                }
            }
            die;
        }
        return $this->fetch();
    }
    //选择我的常用网点
    public function selectMyNetGroup(){

        $where = [];
        $where['cuser'] = Session::get('employee_id');
        $count = Db::table('cg_ti_net_group t')->where($where)->count();
        $data = Db::table('cg_ti_net_group t')->order("t.id desc")->where($where)->paginate(10,$count);

//        echo Db::table('cg_ti')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $t = unserialize($v['net_id']);
            $t = implode(',',$t);
            $t = db('cg_net')->where('id','in',$t)->field('title,id')->select();
            $t2 = [];
            foreach($t as $kk=>$vv){
                $t2[] = $vv['title'];
            }
            $t2 = implode(',',$t2);
            $data[$k]['net_title'] = $t2;
            $data[$k]['net_json'] = json_encode($t);

        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //模板变量
    public function template(){
        //查询我的模板
        $my_t = db('cg_ti_template')->where('cuser',session('employee_id'))->field('id,title')->select();
        $this->assign('my_t',$my_t);

        //全部模板
        $my_t = db('cg_ti_template')->field('id,title')->select();
        $this->assign('all_t',$my_t);


        $my_t_cy = db('cg_ti_template_cy t')->join('cg_ti_template t2','t.tid=t2.id')->where('t.cuser',session('employee_id'))->field('t2.id,t2.title')->order('t.num desc')->limit('5')->select();
        $this->assign('my_t_cy',$my_t_cy);

        //常用模板

    }

    //查看详情
    public function view(){
        $id = $this->request->param('id');
        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');


        //查询明细列表
        if($data['arealat']==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-含税税费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi');//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销金额
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net')->field('net')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('yujiroi');//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['net'=>$v['net'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }

        foreach($list as $k=>$v){
            foreach($v['_child'] as $k1=>$v1){
                if($v1['status']==1){ //异动
                    $start = db('cg_ti_list')->where('id',$v1['refer_id'])->value('start');
                    $end = db('cg_ti_list')->where('id',$v1['refer_id'])->value('end');
                    if($start != $v1['start']&&$end!=$v1['end']){
                        $v['_child'][$k1]['start'] = $start;
                        $v['_child'][$k1]['end'] = $end;
                        $v['_child'][$k1]['ydstart'] = $v1['start'];
                        $v['_child'][$k1]['ydend'] = $v1['end'];
                    }
                }
                $v['_child'][$k1]['eauser_title'] = db('employee')->where('id',$v1['eauser'])->value('em_name');
                if($v1['jxs_id']){
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v1['jxs_id'])->value('title');
                }else{
                    $v['_child'][$k1]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->value('t.jxs');
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v['_child'][$k1]['jxs_id'])->value('title');
                }
                $v['_child'][$k1]['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v['_child'][$k1]['paymethod_title'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');

                $v['_child'][$k1]['jrbm_puser_name'] = db('cg_fijiruzd t')
                    ->join('employee t2','t2.id=t.puser')
                    ->where('t.title',$v1['jrbm'])
                    ->value('t2.em_name');//费用计入部门修改人
                $v['_child'][$k1]['jrbm'] = db('department t')
                    ->join('cg_fijiruzd t2','t2.title = t.id')
                    ->where('t2.id',$v1['jrbm'])
                    ->value('t.de_name');

                $v['_child'][$k1]['jrbm_dp'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $v['_child'][$k1]['jrbm_dp_puser'] = db('cg_fijiru t')->join('employee t2','t2.id=t.puser')->where('t.id',$v1['project'])->value('t2.em_name');
                $v['_child'][$k1]['brand'] = db('pro_brands')->where('id',$v1['brand'])->value('brand_name');
                if($v1['net'])
                    $v['_child'][$k1]['net_title'] = db('cg_net')->where('id',$v1['net'])->value('title');
                $v['_child'][$k1]['productlatval'] = $this->productlatval($v1);
                $v['_child'][$k1]['yujifeiyonglv'] = $v1['totalExpectedSales']?round($v1['fb_shijitourufeiyong']/$v1['hanshui'],2)*100:0;
                $v['_child'][$k1]['xiaoshoudachenglv'] = $v1['totalExpectedSales']?round($v1['fb_shijixiaoliang']/$v1['totalExpectedSales'],2)*100:0;
            }
            $list[$k] = $v;
        }

        $data['list'] = $list;

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net is not null')->group('net')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('fb_shijitourufeiyong');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['yujixiaoliang']?$data['hanshui']/$data['yujixiaoliang']*100:0;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi');//总计-预计rio
        $data['yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao');//总计-已核销
        $data['shijixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang');//总计-实际销量
        $data['xiaoshoudachenglv'] = $data['yujixiaoliang']?$data['shijixiaoliang']/$data['yujixiaoliang']*100:0;

//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);
        return $this->fetch();
    }

    //异动
    public function yd(){
        $id = $this->request->param('id');

        //提交表单
        if($_POST){
            $post_data = $this->request->post('data/a');
            $type = $this->request->post('type');
            //验证异动原因
            $bool = true;
            $oldmxids = [];//异动明细的ids
            foreach($post_data as $k=>$v){
                if(!empty($v['ydreason'])){
                    $bool = false;
                }
                if($v['start']!=''&&$v['end']!=''){
                    if(strtotime($v['start'])>strtotime($v['end'])){
                        echo json_encode(['success'=>false,'msg'=>'活动执行开始时间不能大于结束时间']);die;
                    }
                }
                if($v['end']!=''&&$v['expCanTime']!=''){
                    if(strtotime($v['end'])>strtotime($v['expCanTime'])){
                        echo json_encode(['success'=>false,'msg'=>'预计核销时间不能小于活动结束时间']);die;
                    }
                }
                $oldmxids[] = $v['id'];
            }
            if($bool==true){
                echo json_encode(['success'=>false,'msg'=>'请填写异动原因']);die;
            }

            $insert_sn = $this->produceSN();//生成编号

            $ti = db('cg_ti')->where('id',$id)->field('title,arealat,productlat,jxs_id,attach')->find();

            $insert = [
                'sn'=>$insert_sn,
                'title'=>$ti['title'],
                'arealat'=>$ti['arealat'],
                'productlat'=>$ti['productlat'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
                'old'=>$id,
                'cate_id'=>2//类型 2异动
            ];
            if($type=='save2'){
                $insert['status']=3; //提交工作流，区域领导审批
            }

            $ti_id = db('cg_ti')->insertGetId($insert);//生成新纪录
            //修改附件
            $this->updateAttach2($ti_id);

            db('cg_ti')->where('id',$id)->update(['new'=>$ti_id,'status2'=>1]);//更新旧记录

            $old = db('cg_ti_list')
                ->where('ti_id',$id)
                ->select();

            //构造插入数据
            foreach($old as $k=>$v){
                if(in_array($v['id'],$oldmxids)){
                    foreach($post_data as $k1=>$v1){
                        if($v['id']==$v1['id']){
                            $v = array_merge($v,$v1);
                            $v['start'] = strtotime(trim($v['start']));
                            $v['end'] = strtotime(trim($v['end']));
                            $v['expCanTime'] = strtotime(trim($v['expCanTime']));
                            $v['refer_id'] =  $v1['id'];
                            $v['status'] = 1;//0正常，1已异动
                        }
                    }
                }

                $v['cuser'] = session('employee_id');
                $v['puser'] = session('employee_id');
                $v['ctime'] =  time();
                $v['ptime'] =  time();
                $v['ti_id'] =  $ti_id;
                $v['ydstart'] =  null;
                $v['ydend'] =  null;
                unset($v['id']);//删除id
                $old[$k] = $v;
            }
            $bool = db('cg_ti_list')->insertAll($old);

            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        $data['list'] = db('cg_ti_list')->where('ti_id',$id)->order('net asc')->select();
        foreach($data['list'] as $k=>$v){
            $data['list'][$k]['eauser_title'] = db('employee')->where('id',$v['eauser'])->value('em_name');
            if($v['jxs_id']){
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$v['jxs_id'])->value('title');
            }else{
                $data['list'][$k]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->value('t.jxs');
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$data['list'][$k]['jxs_id'])->value('title');
            }
            $data['list'][$k]['feetype'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $data['list'][$k]['paymethod_title'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $data['list'][$k]['jrbm'] = db('department t')->join('cg_fijiruzd t2','t2.title = t.id')->where('t2.id',$v['jrbm'])->value('t.de_name');
            $data['list'][$k]['jrbm_dp'] = db('cg_fijiru')->where('id',$v['project'])->value('title');
            $data['list'][$k]['brand'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            if($v['net'])
                $data['list'][$k]['net_title'] = db('cg_net')->where('id',$v['net'])->value('title');
            $data['list'][$k]['productlatval'] = $this->productlatval($v);
        }

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net is not null')->group('net')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('fb_shijitourufeiyong');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['hanshui']/$data['yujixiaoliang']*100;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi');//总计-预计rio
        $data['yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao');//总计-已核销
        $data['shijixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang');//总计-实际销量

//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);

        //查询附件
        $attach = Db::table('cg_ti')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch();
    }

    //经销商
    public function jxsview(){
        return $this->fetch();
    }
    //明细详情
    public function dataview(){
        $id = $this->request->param('id');
        $data = db('cg_ti_list')->where('id',$id)->find();
        $this->assign('data',$data);
        return $this->fetch();
    }
    //决策依据
    public function decisionbasis(){
        return $this->fetch();
    }

    //提交工作流
    public function subworkflow(){
        $id = $this->request->param('id');
        $bool = db('cg_ti')->where('id',$id)->update(['status'=>3]);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'提交成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'提交失败']);
        }
    }

    //根据id查找状态
    public function status($id){
        $data = [
            1=>'草稿',
            2=>'已打回',
            3=>'区域领导审批',
            4=>'拆分人审批',
            5=>'集团领导审批',
            6=>'抄送',
            7=>'已归档',
            8=>'已作废',
            9=>'已否决',
        ];
        return $data[$id];
    }

    //根据id查找产品纬度标题
    public function productlat($id){
        $data = [
            1=>'品牌',
            2=>'品类',
            3=>'系列',
            4=>'SKU',
            5=>'单品',
        ];
        return $data[$id];
    }

    //根据id查找产品纬度值
    public function productlatval($v){
        if($v['brand']){
            return db('pro_brands')->where('id',$v['brand'])->value('brand_name');
        }elseif($v['category']){
            return db('pro_category')->where('id',$v['category'])->value('category_name');
        }elseif($v['series']){
            return db('pro_series')->where('id',$v['series'])->value('series_name');
        }elseif($v['sku']){
            return db('pro_sku')->where('id',$v['sku'])->value('sku_name');
        }elseif($v['product']){
            return db('pro_products')->where('id',$v['product'])->value('pro_name');
        }
    }

    //取消
    public function cancel(){
        $id = $this->request->param('id');

        //提交表单
        if($_POST){

            //原单保持原样，取消的部分和未取消的部分分别生成新单
            $post_data = $this->request->post('data/a');
            $type = $this->request->post('type');

            //验证
            $ids = [];
            foreach($post_data as $k=>$v){

                if(trim($v['reason'])==''){
                    echo json_encode(['success'=>false,'msg'=>'请填写取消原因']);die;
                }
                $ids[] = $v['id'];

            }

            $ti = db('cg_ti')->where('id',$id)->find();
            //生成新的取消申请单
            $newSN = $this->produceSN();
            $insert = [
                'sn'=>$newSN,
                'title'=>$ti['title'],
                'arealat'=>$ti['arealat'],
                'productlat'=>$ti['productlat'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
                'old'=>$id,
                'cate_id'=>3 //类型,3取消
            ];
            if($type=='save2'){
                $insert['status']=3; //提交工作流，区域领导审批
            }

            //生成新的取消后申请单
            $new_ti_id = db('cg_ti')->insertGetId($insert);

            //修改附件
            $this->updateAttach2($new_ti_id);

            //生成新的取消后明细
            $insert = [];
            foreach($post_data as $k=>$v){
                $row = db('cg_ti_list')->where('id',$v['id'])->find();
                $row['ctime'] = time();
                $row['ptime'] = time();
                $row['cuser'] = Session::get('employee_id');
                $row['puser'] = Session::get('employee_id');
                $row['ti_id'] = $new_ti_id;
                if(trim($v['reason'])){
                    $row['cancel_reason'] = $v['reason'];
                }

                $row['status'] = 2;//0正常，1已异动，2已取消
                unset($row['id']);
                $insert[] = $row;
            }

            db('cg_ti_list')->insertAll($insert);

            //原单子标记为取消
            $temp_bool = db('cg_ti')->where('id',$id)->update(['new'=>$new_ti_id,'status2'=>2]);
            if($temp_bool===false)
                $bool = false;
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        $data['list'] = db('cg_ti_list')->where('ti_id',$id)->order('net asc')->select();
        foreach($data['list'] as $k=>$v){
            $data['list'][$k]['eauser_title'] = db('employee')->where('id',$v['eauser'])->value('em_name');
            if($v['jxs_id']){
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$v['jxs_id'])->value('title');
            }else{
                $data['list'][$k]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->value('t.jxs');
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$data['list'][$k]['jxs_id'])->value('title');
            }
            $data['list'][$k]['feetype'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $data['list'][$k]['paymethod_title'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $data['list'][$k]['jrbm'] = db('department t')->join('cg_fijiruzd t2','t2.title = t.id')->where('t2.id',$v['jrbm'])->value('t.de_name');
            $data['list'][$k]['jrbm_dp'] = db('cg_fijiru')->where('id',$v['project'])->value('title');
            $data['list'][$k]['brand'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            if($v['net'])
                $data['list'][$k]['net_title'] = db('cg_net')->where('id',$v['net'])->value('title');
            $data['list'][$k]['productlatval'] = $this->productlatval($v);

        }

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net is not null')->group('net')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');

        $this->assign('data',$data);

        //查询附件
        $attach = Db::table('cg_ti')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch();
    }

    //roi报告
    public function roireport(){
        return $this->fetch();
    }
    //反馈
    public function feedback(){
        $id = $this->request->param('id');
        $feedbacktype = $this->request->param('feedbacktype');

        if($_POST){
            if($feedbacktype==0){ //整单反馈
                $actualSales = $this->request->post('actualSales');
                $brief = $this->request->post('brief');
                $arr = $this->request->post('arr/a');

                //验证并构造新数组
                $new_arr = [];
                foreach($arr as $k=>$v){
                    if(empty($v['feetype'])){
                        echo json_encode(['success'=>false,'msg'=>'参数错误']);die;
                    }
                    if(empty($v['real_hanshui'])){
                        echo json_encode(['success'=>false,'msg'=>'实际含税金额不能为空']);die;
                    }
                    if($v['real_shuilv']==''){
                        echo json_encode(['success'=>false,'msg'=>'税率不能为空']);die;
                    }
                    if($v['isVAT']==''){
                        echo json_encode(['success'=>false,'msg'=>'请选择是否增值税']);die;
                    }
                    $arr[$k]['ti_id'] = $id;
                    $arr[$k]['cuser'] = session('employee_id');
                    $arr[$k]['puser'] = session('employee_id');
                    $arr[$k]['ctime'] = time();
                    $arr[$k]['ptime'] = time();
                    $new_arr[$v['feetype']] = $arr[$k];
                }

                //拆分数据
                $mingxi = db('cg_ti_list')
                    ->where('ti_id',$id)
                    ->group('feetype')
                    ->field('feetype')
                    ->select();

                $bool = true;
                //计算平均实际总销量
                $cnt = db('cg_ti_list')->where('ti_id',$id)->count();
                $avgsales = round($actualSales/$cnt,2);
                foreach($mingxi as $k=>$v){
                    //计算实际和预期的比例
                    //查询明细个数
                    $cnt = db('cg_ti_list')
                        ->where(['feetype'=>$v['feetype'],'ti_id'=>$id])
                        ->count();
                    //计算平均每个实际金额
                    $meigeshiji = $new_arr[$v['feetype']]['real_hanshui']/$cnt;
                    $shijiweishui = round($meigeshiji/(1+$new_arr[$v['feetype']]['real_shuilv']/100),2); //实际未税金额

                    $shuilv = $new_arr[$v['feetype']]['real_shuilv'];
                    $isVAT = $new_arr[$v['feetype']]['isVAT'];
                    //更新该费用分类下的明细的实际含税金额
                    $bool2 = db('cg_ti_list')
                        ->where(['feetype'=>$v['feetype'],'ti_id'=>$id])
                        ->update([
                            'fb_shijitourufeiyong'=>$meigeshiji,
                            'fb_shijiweishui'=>$shijiweishui,
                            'fb_shuilv'=>$shuilv,
                            'fb_isVAT'=>$isVAT,
                            'fb_shijixiaoliang'=>$avgsales,
                            'fb_brief'=>$brief,
                            ]);
                    if(false === $bool2){
                        $bool = false;
                    }
                }

                //反馈到cg_ti
                $bool2 = db('cg_ti')
                    ->where('id',$id)
                    ->update(['fb'=>1, //是否反馈，0否，1是
                        'fb_cate'=>1,//反馈类型，1整单，2网点
                        'fb_actualSales'=>$actualSales,//实际费用
                        'fb_brief'=>$brief] //备注
                    );

                if(false === $bool2){
                    $bool = false;
                }

                //反馈到all_ti_feeback_list
                $fb_id = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$id])
                    ->value('id');
                if($fb_id==0){
                    $newSN = $this->producefbSN();
                    $fb_id = db('all_ti_feeback_list')->insertGetId([
                        'no'=>$newSN,
                        'type'=>1,
                        'apply_id'=>$id,
                        'c_user_id'=>session('employee_id'),
                        'created_on'=>date('Y-m-d H:i:s'),
                        'is_deleted'=>0,
                        'is_actived'=>1,
                        'state'=>2,
                        'remark'=>$brief,
                    ]);
                    if(false===$fb_id){
                        $bool = false;
                    }

                    //反馈到cg_ti
                    $bool2 = db('cg_ti')
                        ->where('id',$id)
                        ->update(['fd_id'=>$fb_id]);

                    if(false===$bool2){
                        $bool = false;
                    }
                }

                //修改附件
                $this->updateAttach_fb($fb_id);

                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'反馈成功']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'反馈失败']);
                }
            }else{ //按网点反馈提交
                $brief = $this->request->post('brief');
                $arr = $this->request->post('arr/a');

                //验证
                foreach($arr as $k=>$v){
                    if(empty($v['realsales'])){
                        echo json_encode(['success'=>false,'msg'=>'实际总销量不能为空']);die;
                    }
                    if(empty($v['realamount'])){
                        echo json_encode(['success'=>false,'msg'=>'实际未税金额不能为空']);die;
                    }
                    if($v['real_shuilv']==''){
                        echo json_encode(['success'=>false,'msg'=>'税率不能为空']);die;
                    }
                    if($v['isVAT']==''){
                        echo json_encode(['success'=>false,'msg'=>'请选择是否增值税']);die;
                    }

                }

                $productlat = $this->request->post('productlat');
                switch ($productlat){
                    case 1:
                        $product = 'brand';
                        break;
                    case 2:
                        $product = 'category';
                        break;
                    case 3:
                        $product = 'series';
                        break;
                    case 4:
                        $product = 'sku';
                        break;
                    case 5:
                        $product = 'product';
                        break;
                }
                $bool = true;
                //反馈到cg_ti_list
                foreach($arr as $k=>$v){
                    $cnt = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net'],$product=>$v['pid']])
                        ->count();
                    $fb_shijixiaoliang = round($v['realsales']/$cnt,2); //实际销量
                    $fb_realamount = round($v['realamount']/$cnt,2); //实际未税
                    $shijihanshui = round($fb_realamount*(1+$v['real_shuilv']/100),2); //实际含税金额
                    //计算实际销量的平均值
                    $bool2 = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net'],$product=>$v['pid']])
                        ->update([
                           'fb_shijixiaoliang'=>$fb_shijixiaoliang,
                           'fb_shijiweishui'=>$fb_realamount,
                           'fb_shuilv'=>$v['real_shuilv'],
                           'fb_isVAT'=>$v['isVAT'],
                           'fb_shijitourufeiyong'=>$shijihanshui,
                            'fb_brief'=>$brief,
                            'fb_time'=>time(),
                            'fb_user'=>time(),
                        ]);
                    if(false===$bool2){
                        $bool = false;
                    }
                }
                //反馈到cg_ti
                $bool2 = db('cg_ti')
                    ->where('id',$id)
                    ->update(['fb'=>1,'fb_cate'=>2,'fb_brief'=>$brief]);
                if(false===$bool2){
                    $bool = false;
                }

                //反馈到all_ti_feeback_list
                $fb_id = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$id])
                    ->count();
                if($fb_id==0){
                    $newSN = $this->producefbSN();
                    $fb_id = db('all_ti_feeback_list')->insertGetId([
                        'no'=>$newSN,
                        'type'=>1,
                        'apply_id'=>$id,
                        'c_user_id'=>session('employee_id'),
                        'created_on'=>date('Y-m-d H:i:s'),
                        'is_deleted'=>0,
                        'is_actived'=>1,
                        'state'=>2,
                        'remark'=>$brief,
                    ]);
                    if(false===$fb_id){
                        $bool = false;
                    }

                    //反馈到cg_ti
                    $bool2 = db('cg_ti')
                        ->where('id',$id)
                        ->update(['fd_id'=>$fb_id]);

                    if(false===$bool2){
                        $bool = false;
                    }
                }

                //修改附件
                $this->updateAttach_fb($fb_id);

                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'反馈成功']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'反馈失败']);
                }
            }

            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();

        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');

        if($feedbacktype=='0'){ //整单反馈
            //区域纬度
            if($data['arealat'] == 1){
                $arealat = '经销商数';
            }else{
                $arealat = '网点数';
            }

            //产品纬度
            if($data['productlat'] == 1){
                $productlat = '品牌数';
            }elseif($data['productlat'] == 2){
                $productlat = '品类数';
            }elseif($data['productlat'] == 3){
                $productlat = '系列数';
            }elseif($data['productlat'] == 4){
                $productlat = 'sku数';
            }elseif($data['productlat'] == 5){
                $productlat = '产品数';
            }

            $this->assign([
                'arealat'=>$arealat,
                'productlat'=>$productlat
            ]);

            //按照费用科目做统计
            $list = db('cg_ti_list')->where('ti_id',$id)->group('feetype')->select();
            foreach($list as $k=>$v){
                $list[$k]['feetype_title'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');

                //区域纬度
                if($data['arealat'] == 1){
                    $list[$k]['arealats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('jxs_id');
                }else{
                    $list[$k]['arealats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('net');
                }

                //产品纬度
                if($data['productlat'] == 1){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('brand');
                }elseif($data['productlat'] == 2){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('category');
                }elseif($data['productlat'] == 3){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('series');
                }elseif($data['productlat'] == 4){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('sku');
                }elseif($data['productlat'] == 5){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('product');
                }

                //预计含税金额
                $list[$k]['amounts'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('hanshui');
            }
            $data['hanshuis'] = db('cg_ti_list')->where('ti_id',$id)->sum('hanshui');
            $data['list'] = $list;
        }else{ //按照网点反馈
            //区域纬度
            if($data['arealat'] == 1){
                $arealat1 = '经销商编号';
                $arealat2 = '经销商名称';
            }else{
                $arealat1 = '网点编号';
                $arealat2 = '网点名称';
            }
            //产品纬度
            if($data['productlat'] == 1){
                $productlat = '品牌';
            }elseif($data['productlat'] == 2){
                $productlat = '品类';
            }elseif($data['productlat'] == 3){
                $productlat = '系列';
            }elseif($data['productlat'] == 4){
                $productlat = 'sku';
            }elseif($data['productlat'] == 5){
                $productlat = '产品';
            }
            $this->assign([
                'arealat1'=>$arealat1,
                'arealat2'=>$arealat2,
                'productlat'=>$productlat
            ]);

            $list = db('cg_ti_list')->where('ti_id',$id)->group('net')->select();

            $list2 = [];
            foreach($list as $k=>$v){

                $arealat_sn = db('cg_net')->where('id',$v['net'])->value('sn');
                $arealat_title = db('cg_net')->where('id',$v['net'])->value('title');

                //按照产品分组
                if($data['productlat'] == 1){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net']])
                        ->group('brand')
                        ->field('net,brand p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_brands')->where('id',$v1['p_id'])->value('brand_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 2){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net']])
                        ->group('category')
                        ->field('net,category p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_category')->where('id',$v1['p_id'])->value('category_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 3){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net']])
                        ->group('series')
                        ->field('net,series p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_series')->where('id',$v1['p_id'])->value('series_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 4){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net']])
                        ->group('sku')
                        ->field('net,sku p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_sku')->where('id',$v1['p_id'])->value('sku_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 5){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net'=>$v['net']])
                        ->group('product')
                        ->field('net,product p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_products')->where('id',$v1['p_id'])->value('pro_name');
                        $list2[] = $v1;
                    }
                }
            }
            $data['list'] = $list2;
            $data['totalExpectedSales'] = round(db('cg_ti_list')->where('ti_id',$id)->sum('totalExpectedSales'),2);
            $data['totalAmount'] = round(db('cg_ti_list')->where('ti_id',$id)->sum('amount'),2);

        }

        $this->assign('data',$data);
        if($feedbacktype == 0){
            return $this->fetch();
        }else{
            return $this->fetch('feedbackbynet');
        }
    }


    //核销-按照网点核销
    public function writeoff(){
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type');
        $where = [];
        $where['ti_id'] = ['in',$tiids];
        if($type!=null){
            $where['hx_status'] = $type;
        }

        //查询申请单
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['jxs_sn'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('sn');
        $list = db('cg_ti_list')->where($where)->limit(0,10)->select(); //先加载两条
//        echo db('cg_ti_list')->getLastSql();
        if($data['arealat']==2){ //区域纬度选择经销商
            $data['area_title'] = '网点名称';
            $data['area_title2'] = '系统名称';
        }

        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }
        foreach($list as $k=>$v){
            if($data['arealat']==2) { //区域纬度选择经销商
                $list[$k]['net_title'] = db('cg_net')->where('id',$v['net'])->value('title');
                $list[$k]['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net'])->value('t.title');
            }
            if($data['productlat']==1) { //品牌
                $list[$k]['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($data['productlat']==2) { //品类
                $list[$k]['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($data['productlat']==3) { //系列
                $list[$k]['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($data['productlat']==4) { //sku
                $list[$k]['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }else{
                $list[$k]['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }
            $list[$k]['shijitourujine'] = $list[$k]['fb_shijitourufeiyong'];
            $list[$k]['weihexiaojine'] = $list[$k]['shijitourujine']-$v['hx_yihexiao'];
        }

        $data['list'] = $list;
        $this->assign('data',$data);

        //查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);
        return $this->fetch();
    }

    //按照整单核销
    public function writeoff2(){
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type'); //状态
        $where = [];
        $where['ti_id'] = ['in',$tiids];
        if($type!=null){
            $where['hx_status'] = $type;
        }

        //查询申请单
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['jxs_sn'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('sn');
        $list = db('cg_ti_list')->where($where)->group('ti_id,paymethod')->limit(0,10)->select(); //先加载两条
        $data['area_title'] = '网点';
        $data['product_title'] = '产品纬度';

        foreach($list as $k=>$v){
            $list[$k]['ti_title'] = db('cg_ti')->where('id',$v['ti_id'])->value('title');
            $list[$k]['ti_ctime'] = db('cg_ti')->where('id',$v['ti_id'])->value('ctime');
            if($data['arealat']==2) { //区域纬度选择经销商
                //网点个数
                $list[$k]['net_num'] = db('cg_ti_list')
                    ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                    ->count('DISTINCT net');
            }
            //费用科目
            $list[$k]['feetype'] = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->count('DISTINCT feetype');

            $temp = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT brand');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT category');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT series');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT sku');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT product');

            $list[$k]['product_name'] = $temp;

            $list[$k]['shijitourujine'] = db('cg_ti_feebackbynet')->where('list_id',$v['id'])->value('realamount');
            $list[$k]['weihexiaojine'] = $list[$k]['shijitourujine']-$v['hx_yihexiao'];
        }

        $data['list'] = $list;
        $this->assign('data',$data);

        //查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);
        return $this->fetch();
    }

    //加载更多核销明细
    public function hexiaomore(){
        $listrows = 10;
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type');
        $where = [];
        $where['ti_id'] = ['in',$tiids];
        if($type!=null){
            $where['hx_status'] = $type;
        }
        $page = $this->request->param('page');
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $list = db('cg_ti_list')->where($where)->page($page,$listrows)->select(); //先加载两条
//        echo db('cg_ti_list')->getLastSql();
        foreach($list as $k=>$v){
            if($data['arealat']==2) { //区域纬度选择经销商
                $list[$k]['net_title'] = db('cg_net')->where('id',$v['net'])->value('title');
                $list[$k]['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net'])->value('t.title');
            }
            if($data['productlat']==1) { //品牌
                $list[$k]['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($data['productlat']==2) { //品类
                $list[$k]['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($data['productlat']==3) { //系列
                $list[$k]['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($data['productlat']==4) { //sku
                $list[$k]['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }else{
                $list[$k]['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }
            $list[$k]['shijitourujine'] = db('cg_ti_feebackbynet')->where('list_id',$v['id'])->value('realamount');
            $list[$k]['weihexiaojine'] = $list[$k]['shijitourujine']-$v['hx_yihexiao'];
            $list[$k]['shenqingren'] = db('employee')->where('id',$v['cuser'])->value('em_name');
        }


        foreach($list as $k=>$v){
            $no = $page*$listrows+$k+1;
            $link1 = url('view',['id'=>$data['id']]);
            $title1 = isset($v['net_title'])?'<a href="javascript:;">'.$v['net_title'].'</a>':'无';
            $title2 = isset($v['system_title'])?'<a href="javascript:;">'.$v['system_title'].'</a>':'无';
            $feiyongkemu3 = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $rand = mt_rand();
            $link2 = url('buyuhexiao',['id'=>$v['id']]);
            $link3 = db('cg_ti_feeback')->where('ti_id',$v['id'])->value('real_hanshui');
            echo <<<EOF
<tr class="data">
                <td>{$no}</td>
                <td><input type="checkbox" name="items" class="form-control" value="{$v['id']}"></td>
                <td>{$v['shenqingren']}</td>
                <td><a href="{$link1}">{$data['sn']}</a></td>
                <td>{$data['sn']}-{$v['sn']}</td>
                <td>无</td>
                <td>{$title1}</td>
                <td>{$title2}</td>
                <td>{$v['product_name']}</td>
                <td>{$feiyongkemu3}</td>
                <td class="ObjectNum">{$v['shijitourujine']}</td>
                <td class="ObjectNum">{$v['hx_yihexiao']}</td>
                <td class="ObjectNum">{$v['weihexiaojine']}</td>
                <td><input name="weishuihexiaojine" type="text" class="form-control" value="{$v['weihexiaojine']}" style="min-width: 100px;width: 100px"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="1">有
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="0">无
                        </label>
                    </div>
                </td>
                <td><input type="text" name="fapiaohao" class="form-control"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="1">是
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="0" checked>否
                        </label>
                    </div>
                </td>
                <td><input type="text" style="min-width: 60px;width: 60px;" class="form-control" name="shuilv">%</td>
                <td><input type="text" style="min-width: 80px;width: 80px;" class="form-control" name="shuijin"></td>
                <td><input type="text" class="form-control" placeholder="" name="hanshuihexiaojine"></td>
                <td><input type="text" class="form-control" placeholder="" name="shijitourujine"></td>
                <td><input type="checkbox" name="yuebuhexiao" class="form-control"></td>
                <td><input type="text" class="form-control layer-date" name="huodongkaishiriqi" onclick="laydate()"></td>
                <td><select name="zhifufangshi"  class="form-control">
                    <option value="0">货补</option>
                    <option value="1">账扣</option>
                    <option value="2">现金</option>
                    <option value="3">转账</option>
                </select></td>
                <td><input type="text" name="beizhu" class="form-control"></td>
                <td>
                    <button type="button" class="btn-info buyuhexiao" data-link="{$link2}" data-shijitouru="{$link3}" data-yihexiao="{$v['hx_yihexiao']}">本条不予核销</button>
                </td>
            </tr>
EOF;

        }
    }

    //更换经销商
    public function changejxs(){
        //查询所有经销商
        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $this->assign([
            'sn'=>$sn,
            'title'=>$title,
        ]);
        $where = [];
        $where['stuff'] = ['like','%'.session('employee_id').'%'];
        if($sn){
            $where['sn'] = ['like','%'.$sn.'%'];
        }
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        $data = db('cg_jxs')->field('id,sn,title')
            ->where($where)
            ->select();
        //echo db('cg_jxs')->getLastSql();
        $sum1 = 0;
        $sum2 = 0;
        $sum3 = 0;
        $sum4 = 0;
        $sum5 = 0;
        $sum6 = 0;
        foreach($data as $k=>$v){
            $data[$k]['yipizhun'] = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->join('cg_ti_list t3','t3.ti_id=t2.id')
                ->where(['t2.jxs_id'=>$v['id'],'t.state'=>'3'])
                ->sum('t3.fb_shijitourufeiyong'); //已批准--反馈的批准含税金额
            $sum1 += $data[$k]['yipizhun'];
            $data[$k]['yipizhun'] = round($data[$k]['yipizhun'],2);

            $data[$k]['yihexiao'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->where(['t.jxs_id'=>$v['id'],'t.status'=>2])
                ->sum('pizhunhanshui'); //已核销--已批准的核销含税金额
            $sum2 += $data[$k]['yihexiao'];

            //未核销
            $data[$k]['shenqingzhong'] = db('cg_ti_hexiao t')
                ->where(['t.status'=>1,'t.jxs_id'=>$v['id']])
                ->sum('t.tax');//申请中--已提交工作流
            $sum3 += $data[$k]['yihexiao'];

            //未申请
            $data[$k]['weishenqing'] = db('cg_ti_hexiao t')
                ->where(['t.status'=>0,'t.jxs_id'=>$v['id']])
                ->sum('t.tax');//未申请--生成了核销申请单-已存为草稿-但未提交工作流
            $sum4 += $data[$k]['weishenqing'];

            //不予核销
            $data[$k]['buyuhexiao'] = db('cg_ti_list t')
                ->join('cg_ti t2','t.ti_id=t2.id')
                ->where(['t.hx_status'=>2,'t2.jxs_id'=>$v['id']])
                ->sum('t.hx_yihexiao2');//已核销含税
            $fb_shijitourufeiyong = db('cg_ti_list t')
                ->join('cg_ti t2','t.ti_id=t2.id')
                ->where(['t.hx_status'=>2,'t2.jxs_id'=>$v['id']])
                ->sum('t.fb_shijitourufeiyong');//实际投入金额含税
            $data[$k]['buyuhexiao'] = $fb_shijitourufeiyong-$data[$k]['buyuhexiao'];
            $sum5 += $data[$k]['buyuhexiao'];

            //可以核销
            $data[$k]['kehexiao'] = $data[$k]['yipizhun']-$data[$k]['yihexiao']-$data[$k]['shenqingzhong']- $data[$k]['weishenqing'] -$data[$k]['weishenqing']-$data[$k]['buyuhexiao'];
            $sum6 += $data[$k]['kehexiao'];
        }
        $sum1 = round($sum1,2);
        $sum2 = round($sum2,2);
        $sum3 = round($sum3,2);
        $sum4 = round($sum4,2);
        $sum5 = round($sum5,2);
        $sum6 = round($sum6,2);
        $this->assign([
            'data'=>$data,
            'sum1'=>$sum1,
            'sum2'=>$sum2,
            'sum3'=>$sum3,
            'sum4'=>$sum4,
            'sum5'=>$sum5,
            'sum6'=>$sum6,
        ]);
//        dump($data);

        return $this->fetch();
    }

    //更换经销商后
    public function changejxsafter(){
        $id = $this->request->param('id');//经销商id
        $data = db('cg_jxs')->where('id',$id)->find();

        $showtype = $this->request->get('showtype');//显示类型
        $w = [];
        $w['jxs_id'] = $id;
        if($showtype==1){  //只显示可核销的
            $w['hx_status']=0;
        }

        $list = db('cg_ti')->where($w)->select();
        //echo db('cg_ti')->getLastSql();
        $sum1 = 0;
        $sum2 = 0;
        $sum3 = 0;
        $sum4 = 0;
        $sum5 = 0;

        foreach($list as $k=>$v){
            $list[$k]['cuser_name'] = db('employee')->where('id',$v['cuser'])->value('em_name');
            $list[$k]['yipizhun'] = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->join('cg_ti_list t3','t3.ti_id=t2.id')
                ->where(['t2.id'=>$v['id'],'t.state'=>'3'])
                ->sum('t3.fb_shijitourufeiyong'); //已批准--反馈的批准含税金额
            $sum1 += $list[$k]['yipizhun'];

            $listids = db('cg_ti_list')->where('ti_id',$v['id'])->column('id');//按照ti_id查询listid
            $listids = implode(',',$listids);
            $hexids = db('cg_ti_hexiao')->where(['status'=>2,'jxs_id'=>$id])->column('id');//按照审核状态和jxs_id查hx_id
            $hexids = implode(',',$hexids);
            $list[$k]['yihexiao'] = db('cg_ti_hexiao_list')
                ->where(['list_id'=>['in',$listids],'hx_id'=>['in',$hexids]]) //组合查询条件
                ->sum('pizhunhanshui'); //已核销--已批准的核销含税金额
            $sum2 += $list[$k]['yihexiao'];

            //未核销
            $list[$k]['shenqingzhong'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where(['t.status'=>1,'t3.ti_id'=>$v['id']])
                ->sum('t.tax');//申请中--已提交工作流
            $sum3 += $list[$k]['yihexiao'];

            //未申请
            $list[$k]['weishenqing'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where(['t.status'=>0,'t3.ti_id'=>$v['id']])
                ->sum('t.tax');//未申请--生成了核销申请单-已存为草稿-但未提交工作流
            $sum4 += $list[$k]['weishenqing'];

            //不予核销
            $fb_shijitourufeiyong = db('cg_ti_list t')
                ->where(['t.hx_status'=>2,'ti_id'=>$v['id']])
                ->sum('t.fb_shijitourufeiyong');//实际投入金额含税

            $fb_shijitourufeiyong = db('cg_ti_list t')
                ->where(['t.hx_status'=>2,'ti_id'=>$v['id']])
                ->sum('t.fb_shijitourufeiyong');//实际投入金额含税

            $list[$k]['buyuhexiao'] = $fb_shijitourufeiyong;

            //可以核销
            $data[$k]['kehexiao'] = $list[$k]['yipizhun']-$list[$k]['yihexiao']-$list[$k]['shenqingzhong']- $list[$k]['weishenqing'] -$list[$k]['weishenqing']-$list[$k]['buyuhexiao'];
            $sum5 += $list[$k]['kehexiao'];

        }
        $sum1 = round($sum1,2);
        $sum2 = round($sum2,2);
        $sum3 = round($sum3,2);
        $sum4 = round($sum4,2);
        $sum5 = round($sum5,2);
        $data['list'] = $list;
        $this->assign('data',$data);
        $this->assign([
            'data'=>$data,
            'sum1'=>$sum1,
            'sum2'=>$sum2,
            'sum3'=>$sum3,
            'sum4'=>$sum4,
            'sum5'=>$sum5,
        ]);
        return $this->fetch();
    }

    //设置发票信息
    public function setInvoice(){
        return $this->fetch();
    }

    //设置本条不予核销
    public function buyuhexiao(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti_list')->where(array('id'=>$id))->update(['hx_status'=>2]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"操作成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"操作失败"
            ]);die;
        }
    }

    //生成核销预览
    public function makehxpreview(){
        if($_POST){
            $notax = $this->request->post('notax');
            $tax = $this->request->post('tax');
            $shuijinheji = $this->request->post('shuijinheji');
            $data = $this->request->post('data/a');
            foreach($data as $k=>$v){

                $valid = new Valid([
                   'weishuihexiaojine|未税核销金额'=>'required|number',
                   'youwufapiao|有无发票'=>'required',
                   'fapiaohao|发票号'=>'required',
                   'shizengzhishui|是否增值税'=>'required',
                   'shuilv|税率'=>'required|number',
                   'shuijin|税金'=>'required|number',
                   'hanshuihexiaojine|含税核销金额'=>'required|number',
                   'shijitourujine|实际投入金额'=>'required|number',
//                   'yuebuhexiao|余额不予核销'=>'required',
                   'huodongkaishiriqi|活动开始日期'=>'required|dateFormat=Y-m-d',
                   'zhifufangshi|支付方式'=>'required',
                   'beizhu|备注'=>'required',
                ]);
                if($valid->check($v)){
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$valid->getError()
                    ]);die;
                }

                $data[$k]['huodongkaishiriqi'] = strtotime($v['huodongkaishiriqi']);
                $data[$k]['cuser'] = session('employee_id');
                $data[$k]['puser'] = session('employee_id');
                $data[$k]['ctime'] = time();
                $data[$k]['ptime'] = time();
                $data[$k]['ti_id'] = $v['ti_id'];
            }

            //查询jxs_id

            $jxs_id = db('cg_ti')->where('id',$data[0]['ti_id'])->value('jxs_id');

            //插入核销主表
            db('cg_ti_hexiao')->insert([
                'cuser'=>session('employee_id'),
                'puser'=>session('employee_id'),
                'ctime'=>time(),
                'ptime'=>time(),
                'notax'=>$notax,
                'tax'=>$tax,
                'jxs_id'=>$jxs_id,
                'shuijinheji'=>$shuijinheji,
            ]);
            $hx_id = db('cg_ti_hexiao')->getLastInsID();

            //附上hx_id
            foreach($data as $k=>$v){
                $data[$k]['hx_id'] = $hx_id;
            }

            //插入明细
            $bool = db('cg_ti_hexiao_list')->insertAll($data);
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok','hx_id'=>$hx_id]);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }

    //核销预览
    public function hxpreview(){

        $data = $this->request->post('data');
        $data = json_decode($data);
        dump($data);die;
        foreach($data as $k=>$v){
            $v['ti_sn'] = db('cg_ti')->where('id',$v['ti_id'])->value('sn');
            $list_row = db('cg_ti_list')->where('id',$v['list_id'])->find();
            $v['list_sn'] = $list_row['sn'];
            $v['cuser_title'] = db('employee')->where('id',$list_row['cuser'])->value('em_name');
            $v['cuser_dep'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$list_row['cuser'])->value('t.de_name');
            if($list_row['arealat']==2){
                $v['net_title'] = db('cg_net')->where('id',$list_row['net'])->value('title');
                $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$list_row['net'])->value('t.title');
            }else{
                $v['net_title'] = '';
                $v['system_title'] = '';
            }

            if($list_row['productlat']==1) { //品牌
                $data[$k]['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($productlat==2) { //品类
                $data[$k]['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($productlat==3) { //系列
                $data[$k]['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($productlat==4) { //sku
                $data[$k]['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }else{
                $data[$k]['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }

            $data[$k] = $v;
        }
        foreach($data as $k=>$v){



            $data[$k]['shijitourujine'] = db('cg_ti_feebackbynet')->where('list_id',$v['list_id'])->value('realamount');
            $data[$k]['weihexiaojine'] = $data[$k]['shijitourujine']-$v['hx_yihexiao'];
            $data[$k]['zhifufangshi'] = db('cg_paymethod')->where('id',$v['zhifufangshi'])->value('title');
        }

        $tax = $this->request->post('tax');
        $notax = $this->request->post('notax');
        $shuijinheji = $this->request->post('shuijinheji');
        $tiids = $this->request->post('tiids');
//
//        if($_POST){
//            $data = [];
//            $data['beizhu'] = $this->request->post('beizhu');
//            $data['guidangtixing'] = $this->request->post('guidangtixing');
//            $bool = db('cg_ti_hexiao')->where('id',$hx_id)->update($data);
//            if(false!==$bool){
//                $this->updateAttach3($hx_id);
//                echo json_encode(['success'=>true,'msg'=>'ok']);
//            }else{
//                echo json_encode(['success'=>false,'msg'=>'error']);
//            }
//            die;
//        }


        $jxs_id = db('cg_ti')->where('id',$data[0]->ti_id)->value('jxs_id');
        $productlat = db('cg_ti')->where('id',$data[0]->ti_id)->value('productlat');
        $cuser = db('cg_jxs')->where('id',$jxs_id)->value('cuser');
        $basic['jxs_title'] = db('cg_jxs')->where('id',$jxs_id)->value('title');
        $basic['cuser_title'] = db('employee')->where('id',$cuser)->value('em_name');


        $basic['area_title'] = '网点名称';
        $basic['area_title2'] = '系统名称';


        if($productlat==1) { //产品纬度
            $basic['product_title'] = '品牌';
        }elseif($productlat==2) {
            $basic['product_title'] = '品类';
        }elseif($productlat==3) {
            $basic['product_title'] = '系列';
        }elseif($productlat==4) {
            $basic['product_title'] = 'sku';
        }elseif($productlat==5) {
            $basic['product_title'] = '产品';
        }

        $this->assign('basic',$basic);


        //实际投入金额合计
        $sum_shijitourujine = $this->array_sum($data,'shijitourujine');
        $sum_hx_yihexiao = $this->array_sum($data,'hx_yihexiao');
        $sum_weihexiaojine = $this->array_sum($data,'weihexiaojine');
        $sum_weishuihexiaojine = $this->array_sum($data,'weishuihexiaojine');
        $sum_shuijin = $this->array_sum($data,'shuijin');
        $sum_hanshuihexiaojine = $this->array_sum($data,'hanshuihexiaojine');
        $sum_shijitourujine = $this->array_sum($data,'shijitourujine');

        $this->assign('data',$data);
        $this->assign('sum_shijitourujine',$sum_shijitourujine);
        $this->assign('sum_hx_yihexiao',$sum_hx_yihexiao);
        $this->assign('sum_weihexiaojine',$sum_weihexiaojine);
        $this->assign('sum_weishuihexiaojine',$sum_weishuihexiaojine);
        $this->assign('sum_shuijin',$sum_shuijin);
        $this->assign('sum_hanshuihexiaojine',$sum_hanshuihexiaojine);
        $this->assign('sum_shijitourujine',$sum_shijitourujine);

        return $this->fetch();
    }

    //返回二维数组中的某二维key的合计
    public function array_sum($arr,$key){
        $sum = 0;
        foreach($arr as $k=>$v){
            $sum += $v[$key];
        }
        return $sum;
    }
}
